/*
 * @Author: DUST
 * @Date: 2023-06-07 11:09:04
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-27 09:52:42
 * @FilePath: \vite-project\src\class\pageDetails.ts
 * @Description: 
 * undefined
 */

import { Ajax } from "@/interface";
import { AxiosResponse } from "axios";
import { Ref, ref } from "vue";
import router from "@/router";
import routerStore from "@/store/router";
import { RouteLocationMatched } from "vue-router";

interface detailsDataBase {
  id: number;
}

class Details<T extends detailsDataBase> {
  /**
   * @description: 详情数据源
   */  
  private _detailsData = ref<T>() as Ref<T>;
  public get detailsData() : Ref<T> {
    return this._detailsData;
  }
  /**
   * @description: 详情数据源
   */  
  private _pathMap = ref<RouteLocationMatched[]>([]) as Ref<RouteLocationMatched[]>;
  public get pathMap() : Ref<RouteLocationMatched[]> {
    return this._pathMap;
  }
  /**
   * @description: 数据加载loading
   */  
  private _loading = ref<boolean>(false);
  public get loading() : Ref<boolean> {
    return this._loading;
  };
  /**
   * @description: 获取数据的接口
   */  
  private _Func: (id: number) => Promise<AxiosResponse<Ajax<T>>>;
  /**
   * @description: 获取详情的id参数
   */  
  private _paramsId = ref<number>();
  /**
   * @description: 接口完成后的回调函数
   */  
  private _callbaclFunc: ((res: T) => void) | undefined;
  
  constructor({
    paramsId,
    routeMatched = [],
    func,
    callBackFunc,
  }: {
    paramsId: number;
    routeMatched: RouteLocationMatched[];
    func: (id: number) => Promise<AxiosResponse<Ajax<T>>>,
    callBackFunc?: (res: T) => void;
  }) {
    this._Func = func;
    this._paramsId.value = paramsId;
    this._pathMap.value = routeMatched;
    if(callBackFunc) this._callbaclFunc = callBackFunc;
    this.getData();
  }
  /**
   * @description: 获取详情数据
   * @param {number} id：获取数据的ID参数
   */  
  public getData = (id?: number) => {
    this._loading.value = true;
    if(id) this._paramsId.value = id;
    this._Func(this._paramsId.value as number).then((res: AxiosResponse<Ajax<T>>) => {
      this._detailsData.value = res.data.data;
      if(this._callbaclFunc) this._callbaclFunc(res.data.data);
    }).finally(() => {
      this._loading.value = false;
    })
  }
  /**
   * @description: 返回上一页
   */  
  public goBack() {
    router.push(routerStore.lastPath as string);
  }
  /**
   * @description: 跳转指定路由表
   */  
  public goPath(path: string) {
    router.push(path);
  }
}

export default Details;
